class Solution
{
    int m, n;
    int dx[4] = { 0, 0, -1, 1 }, dy[4] = { 1, -1, 0, 0 };
    int prev;
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color)
    {
        m = image.size(), n = image[0].size();
        if (image[sr][sc] == color) return image;

        prev = image[sr][sc];
        dfs(image, sr, sc, color);
        return image;
    }

    void dfs(vector<vector<int>>& image, int i, int j, int color)
    {
        image[i][j] = color;

        for (int k = 0; k < 4; k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && y >= 0 && x < m && y < n && image[x][y] == prev)
            {
                dfs(image, x, y, color);
            }
        }
    }
};